package org.example.controller;

import dto.LoginDTO;
import entity.Users;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.constant.JwtClaimsConstant;
import org.example.constant.UrlConstant;
import org.example.properties.JwtProperties;
import org.example.result.Result;
import org.example.service.AccountService;
import org.example.utils.JwtUtil;
import org.example.utils.ThreadLocalUtil;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Validated
@Tag(name = "账户模块", description = "账号基础操作")
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/account")
public class AccountController {

    private final AccountService accountService;

    private final JwtProperties  jwtProperties;

    private final RedisTemplate redisTemplate;

    //登录
    @Operation(summary = "登录")
    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDTO loginDto) {
        Users user = accountService.findByUsername(loginDto.getUsername());

        if (user == null) {
            return Result.error("用户不存在");
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(5);
        if (encoder.matches(loginDto.getPassword(), user.getPassword())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put(JwtClaimsConstant.USER_ID, user.getUserId());
            claims.put(JwtClaimsConstant.USERNAME, user.getUsername());
            String token = JwtUtil.getToken(claims,jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl());
            redisTemplate.opsForValue().set(JwtClaimsConstant.TOKEN, token, 1, TimeUnit.HOURS);
            //获取用户角色并设置重定向地址
            String redirectUrl = getRedirectUrlForRole(user);
            //创建包含有token和用户角色的Map对象
            Map<String, Object> responseData = new HashMap<>();
            responseData.put(JwtClaimsConstant.REDIRECT_URL, redirectUrl);
            responseData.put(JwtClaimsConstant.TOKEN, token);
            //返回token和用户角色
            return Result.success(responseData);
        }
        return Result.error("密码错误");
    }

    /**
     * 获取个人信息
     * @return
     */
    @Operation(summary = "获取个人信息")
    @GetMapping("/getUserInfo")
    public Result<Users> getUserInfo(){
        Users user = findUserByThreadLocal();
        return Result.success(user);
    }

    /**
     * 退出登录
     * @return
     */
    @Operation(summary = "退出登录")
    @PostMapping("/logout")
    public Result logout(){
        log.info("退出登录");
        // 从Redis中删除token
        redisTemplate.delete(JwtClaimsConstant.TOKEN);
        // 清除ThreadLocal中的用户信息
        ThreadLocalUtil.remove();
        return Result.success();
    }

    //根据用户角色获取重定向地址
    private String getRedirectUrlForRole(Users user) {
        if (user.getRoleId() == 0) {
            return UrlConstant.ADMIN_BASE_URL;
        } else if (user.getRoleId() == 1) {
            return UrlConstant.INSPECTOR_BASE_URL;
        } else if (user.getRoleId() == 2) {
            return UrlConstant.PROCESS_ENGINEER_BASE_URL;
        }else if (user.getRoleId() == 3) {
            return UrlConstant.QUALITY_MANAGER_BASE_URL;
        }else if (user.getRoleId() == 4) {
            return UrlConstant.SUPERVISOR_BASE_URL;
        }
        return "找不到角色";
    }

    //用ThreadLocalUtil获取当前登录的用户信息
    private Users findUserByThreadLocal(){
        //用ThreadLocalUtil获取当前登录的用户信息
        Map<String,Object> map = ThreadLocalUtil.get();
        // 添加空值检查，避免空指针异常
        if (map == null) {
            // 由于JWT拦截器被禁用，ThreadLocal中没有用户信息
            // 这里可以返回一个默认用户或直接返回null
            log.warn("ThreadLocal中没有用户信息，可能是JWT拦截器被禁用");
            return null;
        }
        String username = (String)map.get(JwtClaimsConstant.USERNAME);
        //根据用户名查询用户
        Users user = accountService.findByUsername(username);
        return user;
    }

//  修改信息
    public Result logout(HttpServletRequest request) {

        return Result.success();
    }
}
